<?php
//make a one to many (O2M) table:
function df_list_table($table_info, $current_doc_id, $plugin_cell=''){
	global $modx;
	
	$entries = get_O2M_entries($table_info, $current_doc_id);

	$foreign_keys= $table_info->getForeignKeys();
	
	$summary_fields = $table_info->getSummaryFields();
	
	echo '<tr id="df_table_header_row"">';
	//list summary table header:
	foreach ($summary_fields as $column => $label){
		echo '<th>'.$label.'</th>';
	}
	echo '</tr>';
	
	if ( $modx->db->getRecordCount($entries) > 0 ){
		//list the summary entries:
		while ($row = $modx->db->getRow($entries)) {
			$article_id = $row[$table_info->getPrimaryKey()];

			echo '<tr title="'.$article_id.'" class="clickable">';
			
			foreach ($summary_fields as $column => $label){
				echo produce_table_cell($row, $column, $foreign_keys);
			}
			
			echo df_parse_plugin_cell($plugin_cell, $article_id);
			
			echo '</tr>';

		}
	}else{
		//no entries to display:
		echo "<tr><td colspan='".count($summary_fields)."'>No Records to display from office: '$current_doc_id' in table: '".$table_info->getTableName()."'</td></tr>";
	}
	
} //end df_list_table

//this is a model function to get entries from an o2m table.  could alternatively be stored in the table_info class...
// it might be good to remove the $modx were that to be done.
function get_O2M_entries($table_info, $current_doc_id){
	global $modx;

	//TODO: O2M with multiple foreign keys?!
	//TODO: clean this up to allow standard convention/structure for resource partens?
	//TODO: this should really be part of the model (core)
	$where = '';
	$linked_tables = $table_info->getForeignKeys();
	if (!empty($current_doc_id) && !empty($linked_tables)) {
		$colName = key($linked_tables);
		
		$resource = $modx->db->query("SELECT parent FROM modx_site_content WHERE id=$current_doc_id");
		$parent_id = $modx->db->getRow($resource);
		$parent_id = $parent_id['parent'];
		
		if($colName == 'office_id' && $parent_id == '22'){
			$where .= $colName.'='.$current_doc_id;
		}
	}else{
	}

	return $modx->db->select('*',$table_info->getTableName(), $where);
}

// the first associative foreign key will be taken as the main data item. 
// the bulk of this should really be moved in to the model.. (M2M_table_info class)
function df_list_M2M_table($table_info, $current_doc_id, $plural_name){
	global $modx;
	$summary_fields = array();
	$tables = array();
	$primary_table = $table_info->getPrimaryJoined();  //this is a table_info object
	
	$select = $table_info->getTableName().'.'.$table_info->getResouceIdColName() .', '. 
				$table_info->getTableName().'.'.$table_info->getPrimaryKey() .', '. 
				$table_info->getTableName().'.'.$table_info->getPrimaryJoinedColName();
	$where = $table_info->getTableName().'.'.$table_info->getResouceIdColName().'='.$current_doc_id; //limit to only this page
	

	$tables[] = $table_info->getTableName();
	
	//make a list of all the foreign keys, for use in table cell production:
	
	$linked_tables = $table_info->getRecursivelyLinkedTables();  //this is for when creating a table cell, knowing the foreign keys.
		
	// $all_tables = array_merge($table_info, $all_tables);
	// get all joined foreign keys and tables:
	
	foreach ($linked_tables as $this_table_name => $this_table_info){
			$tables[] = $this_table_info->getTableName();
		
			$where .= ' AND '.$this_table_info->getTableName().'.'.$this_table_info->getPrimaryKey().' = '.$this_table_info->getParentTable()->getTableName().'.'.$this_table_name;
	}
	
	$summary_fields = $table_info->getRecursiveSummaryFields();

	$first = true; $order = '';
	foreach ($summary_fields as $fieldLocator => $fieldTitle){
		if ($first){$first =false; $order .= 'ORDER BY '.$fieldLocator;}
		$as = preg_replace('/\./','OOOO',$fieldLocator);
		$select .= ', '.$fieldLocator.' as '.$as;
	}
		
	
	$from = implode(', ', $tables);
	$query = "SELECT $select FROM $from WHERE $where  $order";
	$M2Mdata = mysql_query($query);
	
	if (!$M2Mdata) {
	    $message  =  mysql_error() . "\nInvalid M2M query: " . $query;
	    die($message);
	}
	
	$thisPageRecords = Array();
	$current_rows = '';
	
	
	
	//print the records belonging to this document/resource:
	if (mysql_num_rows($M2Mdata) == 0){
		echo "<p>No ".$table_info->getTableName()." records found</p>";
	}else{
		$num_current = 0;
		$primaryOther_colName = $table_info->getPrimaryJoinedColName();						
						
		while ($row = $modx->db->getRow($M2Mdata)) {
		
				$id = $row[$table_info->getPrimaryKey()]; //M2Mid
				
				$thisPageRecords[ $row[$primaryOther_colName] ] = ''; //save the positive match values
				
				$o =  '<tr class="';
					$o .= ($num_current & 1) ? 'odd_row' : 'even_row';
				$o .= '">';
				
				
				foreach ($summary_fields as $field_locator => $fieldTitle){
					$as = preg_replace('/\./', 'OOOO', $field_locator);
					if ($field_locator == "products.LOB_id"){ //crappy non DRY code, same as in produce_table_cell :-/
						$resource = mysql_query('SELECT pagetitle FROM modx_site_content WHERE id='.$row[$as]);
						$page = mysql_fetch_assoc($resource);
						$data = $page['pagetitle'];
					}else{
						$data = $row[$as];
					}
					$o .= '<td>'.$data.'</td>';

				}
				$current_rows .= $o.'<td><a class="removeM2M" title="'.$id.'" href="#">Remove from Current</a></td></tr>';
				$num_current++;
		
		}
	}
	
	// echo "as:".$as;
	// echo "<pre>".print_r($linked_tables)."</pre>";
	
	$foreign_keys = $primary_table->getForeignKeys();
	
	
	// print the other records:
	$other_rows = '';
	$O2Mdata = get_O2M_entries($primary_table, '');

	if (mysql_num_rows($O2Mdata) == 0){
		$other_rows .= '<p>No records found</p>';
	}else{
		$num_other = 0;
		
		while ($row = $modx->db->getRow($O2Mdata)){
			$id = $row[$primary_table->getPrimaryKey()];
			if (!isset($thisPageRecords[$id])){ //only set if not in other table

				$o =  '<tr class="';
				$o .= ($num_other & 1) ? 'odd_row' : 'even_row';
				$o .= '">';	
				foreach ($primary_table->getSummaryFields() as $field => $fieldTitle){
					$o .= produce_table_cell($row, $field, $foreign_keys);
				}
				$other_rows .= $o.'<td><a class="addM2M" title="'.$id.'" href="#">Add to Current</a></td></tr>';
				$num_other++;

			}
		}
	}

		//display the tables:
		
		echo "<h2>Current $plural_name ($num_current):</h2>";
		echo '<table class="dftable" cellspacing="0" cellpadding="0" id="df_current_'.$plural_name.'">';
		echo '<tr id="df_table_header_row">';
		// foreach ($primary_table->getSummaryFields() as $field => $fieldTitle){
			// echo '<th>'.$fieldTitle.'</th>';
		// }
		//this needs some clever debugging..
			foreach ($summary_fields as $field => $fieldTitle){
				echo '<th>'.$fieldTitle.'</th>';
			}
		echo '</tr>'.$current_rows.'</table>';
		
		
		echo "<div class='df_filterbox'>Filter $plural_name: <input id='filterbox_$plural_name' type='text'> <a href='#' id='cancel_filter_$plural_name'>X</a></div>";
		
		echo "<br><h2>All $plural_name ($num_other):</h2>";
		echo '<table class="dftable" cellspacing="0" cellpadding="0" id="df_other_'.$plural_name.'">';
		echo '<tr id="df_table_header_row">';
			foreach ($primary_table->getSummaryFields() as $field => $fieldTitle){
				echo '<th>'.$fieldTitle.'</th>';
			}

		echo '</tr>'.$other_rows.'</table>'; 
		
		echo "<div id='data_holder_$plural_name' style='display: none;'>";
		//add the table, serialized, for js to pass to df_move_row
		echo "<input type='hidden' class='M2M_info' value='".urlencode(serialize($table_info))."'>";
		echo "<input type='hidden' class='current_doc_id' value='".$current_doc_id."'>";
		echo "<div style='display: none;' class='additional_M2M_fields'>";
			$other_fields = $table_info->getOtherJoined();
			if (count($other_fields) > 0) {
				require_once(MODX_MANAGER_PATH.'../assets/plugins/dataFrolic/tmplvars2.inc.php'); //for rendering database fields
				require_once(MODX_MANAGER_PATH.'tmplvars.commands.inc.php');
				foreach ($other_fields as $fieldName => $fieldVal){
					// $field_elements = ; //how will this work exactly? maybe it will do option values for me?
					echo "Select $fieldName:<br>";
					//$field_elements = "@SELECT title, id FROM ".$foreign_keys[$fieldName]->getTableName(); //we know obj not str because of condition above
					
					echo renderFormElement2('listbox', $fieldName, '', "@SELECT title, id FROM ".$fieldVal->getTableName(), '');
					echo "<br><br><br>";
				}
			}
		echo "</div>";
		echo "</div>"; //end data holder
		



		//add the js for the table: 
		//function df_M2M_table(tableCurrent, tableOther, dbtable){//jq objects
		echo "<script type='text/javascript'>df_M2M_table(j('#df_current_$plural_name'), j('#df_other_$plural_name'), j('#data_holder_$plural_name'));</script>";
		echo "<script type='text/javascript'>df_filterbox('$plural_name');</script>";
}

function produce_table_cell($row, $fieldName, $linked_tables){
	if (strlen($linked_tables) > 0 && array_key_exists( $fieldName, $linked_tables)){
		$linked_table = $linked_tables[$fieldName];
		
		if (is_object($linked_table)){ //linked table
			
			$title = 'title';  //todo this: update to support other linked table column names
			$resource = mysql_query("SELECT $title FROM ".$linked_table->getTableName().' WHERE '.$linked_table->getPrimaryKey().'='.$row[$fieldName]);
			$row = mysql_fetch_assoc($resource);
			return '<td>'.stripslashes($row[$title]).'</td>';
			
		}else{ // referring to modx parent document
			
			$resource = mysql_query('SELECT pagetitle FROM modx_site_content WHERE id='.$row[$fieldName]);
			$page = mysql_fetch_assoc($resource);
			return '<td>'.$page['pagetitle'].'</td>';
			
		}
	}else{
		return '<td>'.stripslashes($row[$fieldName]).'</td>';
	}
}

?>